package net.esj.basic.utils.algorithm;

import java.util.NoSuchElementException;

import net.esj.basic.utils.StringUtils;

import org.apache.commons.lang.RandomStringUtils;

public abstract class AbstractAlgorithm implements Algorithm{
	
	private AlgoEntity[] items;
	
	abstract void calc();
	
	public AbstractAlgorithm(int count) {
		items = (AlgoEntity[]) new AlgoEntity[count];
	}
	
	public AbstractAlgorithm(AlgoEntity... es) {
		items = es;
	}
	
	public AbstractAlgorithm() {
		items = new AlgoEntity[0];
	}

	public void push(long rate,Object o){
		int len = items.length;
		AlgoEntity[] tmp = new AlgoEntity[len + 1];
		System.arraycopy(items, 0, tmp, 0, len);
		tmp[len] = new AlgoEntity(rate, o);
		items = tmp;
		calc();
	}
	
	protected void remove(Object e){
		if(e == null) throw new NoSuchElementException();
		int len = items.length;
		if(len<=0) throw new IllegalArgumentException();
		
		AlgoEntity[] tmp = new AlgoEntity[len - 1];
		int k = 0;
		for(int i=0;i<items.length;i++){
			if(e.equals(items[i].getTarget())){
				continue;
			}else{
				tmp[k++] = items[i];
			}
		}
		items = tmp;
		calc();
	}

	protected AlgoEntity[] getItems() {
		return items;
	}
	
	public static class AlgoEntity{
		private long rate;
		
		private Object target;
		
		public AlgoEntity(long rate, Object target) {
			this.rate = rate;
			this.target = target;
		}

		public long getRate() {
			return rate;
		}

		public void setRate(long rate) {
			this.rate = rate;
		}

		public Object getTarget() {
			return target;
		}

		public void setTarget(Object target) {
			this.target = target;
		}
	}
}
